package com.appspot.ldsdrawingtool.server.services;

import java.util.HashMap;
import java.util.Map;
import com.appspot.ldsdrawingtool.client.lds.components.LDSClientModel;
import com.appspot.ldsdrawingtool.client.services.stubs.LDSModelUpdaterServiceStub;
import com.appspot.ldsdrawingtool.server.lds.components.LDSModel;
import com.appspot.ldsdrawingtool.shared.SharedStrings;
import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class LDSModelUpdaterServiceImpl extends RemoteServiceServlet implements LDSModelUpdaterServiceStub {
    
    private static Map<String, LDSModel> ldsModels = new HashMap<String, LDSModel>();

    @Override
    public String setLDSModelName(String identifier, String newName) {
        LDSModel ldsModel = getOrLoadLDSModel(identifier);
        if (ldsModel != null) {
            for (String user : UserAccountServiceImpl.channellingUsers) {
                ChannelService channelService = ChannelServiceFactory.getChannelService();
                channelService.sendMessage(new ChannelMessage(user, newName));
            }
            ldsModel.setName(newName);
            return newName;
        }
        
        // Will only happen if there was no persisted model
        return null;
    }
    
    private LDSModel getOrLoadLDSModel(String identifier) {
        // Check the in-memory map first
        LDSModel mappedModel = ldsModels.get(identifier);
        if (mappedModel != null) {
            return mappedModel;
        } 
        else {
            // If it doesn't exist in-memory, then check the data store
            mappedModel = LDSModelStorageService.getModelByIdentifier(identifier);
            if (mappedModel != null) {
                // Grabbed it from the data-store, put it in-memory
                ldsModels.put(identifier, mappedModel);
                return mappedModel;
            }
        }
        // If no model existed then return null
        return null;
    }

    @Override
    public LDSClientModel getDefaultLDSModel() {
        LDSModel defaultLDSModel = getOrLoadLDSModel(SharedStrings.DEFAULT_MODEL_ID);

        // Create and persist the default model if it doesn't exist
        if (defaultLDSModel == null) {
            defaultLDSModel = new LDSModel(SharedStrings.DEFAULT_MODEL_ID, "Default LDS Model Name");
            LDSModelStorageService.persistLDSModel(defaultLDSModel);
        }
        
        LDSClientModel.get().setIdentifier(defaultLDSModel.getIdentifer());
        LDSClientModel.get().setName(defaultLDSModel.getName());
        
        return LDSClientModel.get();
    }

}
